#!/bin/bash

# Docker镜像构建和部署脚本

set -e

# 配置变量
IMAGE_NAME="liured88/unitechoose9"
CONTAINER_NAME="unitechoose9"
PORT="7605"
DATA_DIR="/bak/docker/unitechoose/data"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log() {
    echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

success() {
    echo -e "${GREEN}✅ $1${NC}"
}

error() {
    echo -e "${RED}❌ $1${NC}"
}

warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

echo "========================================"
echo "    Docker镜像构建和部署脚本"
echo "========================================"
echo

log "[1/6] 停止并删除现有容器..."
docker stop $CONTAINER_NAME 2>/dev/null || true
docker rm $CONTAINER_NAME 2>/dev/null || true
success "现有容器已清理"

echo
log "[2/6] 检查必需文件..."

# 检查必需文件
if [ ! -f "backend/main.py" ]; then
    error "backend/main.py 文件不存在"
    error "请确保在项目根目录执行此脚本"
    exit 1
fi

if [ ! -f "frontend/package.json" ]; then
    error "frontend/package.json 文件不存在"
    error "请确保在项目根目录执行此脚本"
    exit 1
fi

if [ ! -f "sample_questions.json" ]; then
    error "sample_questions.json 文件不存在"
    error "请确保在项目根目录执行此脚本"
    exit 1
fi

success "必需文件检查通过"

echo
log "[3/6] 使用优化的Dockerfile构建镜像..."
log "镜像名称: $IMAGE_NAME"
log "构建开始时间: $(date)"

if docker build -f Dockerfile.optimized -t $IMAGE_NAME .; then
    success "镜像构建成功"
    log "构建完成时间: $(date)"
else
    error "镜像构建失败"
    error "请检查构建日志中的错误信息"
    exit 1
fi

echo
log "[4/6] 检查镜像信息..."
docker images $IMAGE_NAME

echo
log "[5/6] 启动容器..."
log "容器名称: $CONTAINER_NAME"
log "端口映射: $PORT:8000"
log "数据目录: $DATA_DIR"

if docker run -d \
    --name $CONTAINER_NAME \
    -p $PORT:8000 \
    -v $DATA_DIR:/app/data \
    --network=mynet \
    --restart unless-stopped \
    $IMAGE_NAME; then
    success "容器启动成功"
else
    error "容器启动失败"
    exit 1
fi

echo
log "[6/6] 检查容器状态..."
sleep 3
docker ps | grep $CONTAINER_NAME || true

echo
echo "========================================"
echo "           部署完成！"
echo "========================================"
echo "容器名称: $CONTAINER_NAME"
echo "访问地址: http://localhost:$PORT"
echo "数据目录: $DATA_DIR"
echo
echo "常用命令:"
echo "  查看日志: docker logs -f $CONTAINER_NAME"
echo "  停止容器: docker stop $CONTAINER_NAME"
echo "  重启容器: docker restart $CONTAINER_NAME"
echo "  进入容器: docker exec -it $CONTAINER_NAME bash"
echo "========================================"

echo
log "等待5秒后显示容器日志..."
sleep 5
echo
echo "=== 容器启动日志 ==="
docker logs $CONTAINER_NAME

echo
echo "脚本执行完成！"
